<?php
/*
 * @Author: LDY dong2406@126.com
 * @Date: 2022-08-08 17:19:07
 */
namespace Ldy\Models;

use Ldy\Model;
use think\facade\Cache;

class SysConfig extends Model{

    //设置字段名称
    // public $fieldsLabel = ["update_time" => "更新时间", "type"=>"类型"];

    // public $fieldsLabelRand = true;

    protected $json = ['fields'];

    protected static $cacheKey = 'config_';

    public static function onAfterInsert(){
        $config = request()->post();
        if(!empty($config)) self::setCache($config);
    }

    public static function onAfterUpdate(){
        $config = request()->post();
        if(!empty($config)) self::setCache($config);
    }

    public static function getItem(String $keys){
        if(!$keys) return false;

        $keyArr = explode('.', $keys);
        $key = static::$cacheKey . $keyArr[0];
        $cache = Cache::get($key);
        if(empty($cache)){
            $tmp = self::where('type', $keyArr[0])->find();
            if(!$tmp) return false;
            $cache =  json_decode(json_encode($tmp->fields),true);
            Cache::set($key, $cache);
        }

        if(count($keyArr) === 1) return $cache;

        $val = '';
        foreach($keyArr as $k=>$v){
            if($k == 0) continue;
            if(!isset($cache[$v])) break;

            $val = $cache[$v];
        }

        return $val;
    }

    private static function setCache($config){
        
        foreach($config as $key=>$val) {
            $ck = self::$cacheKey.$key;
            Cache::set($ck, $val);
        }
    }
 }